from pymilvus import MilvusClient

# 连接服务
client = MilvusClient("http://localhost:19530")

# 清理旧集合
coll_name = "test"
if client.has_collection(coll_name):
    client.drop_collection(coll_name)

# 创建集合
client.create_collection(
    collection_name=coll_name,
    dimension=2,
    primary_field_name="id",
    id_type="int",
    vector_field_name="vec",
    metric_type="L2"
)

# 插入数据
client.insert(
    collection_name=coll_name,
    data=[{"id": 1, "vec": [0.1, 0.2]}, {"id": 2, "vec": [0.3, 0.4]}]
)

# 创建索引（按最低要求传参）
client.create_index(
    collection_name=coll_name,
    field_name="vec",
    index_params={"index_type": "IVF_FLAT", "metric_type": "L2", "params": {"nlist": 10}}
)

# 检索
print(client.search(
    collection_name=coll_name,
    data=[[0.15, 0.25]],
    limit=1
))

# 清理
client.drop_collection(coll_name)
